//
//  SupportVC.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/24/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit

final class SupportViewController: UIViewController {
    
    let data = [
        [
            "image": UIImage(named: "help") as Any,
            "icon": UIImage(named: "dismiss") as Any,
            "text": "Как оставить заявку?",
            "message": "Вы можете создать заявку на главной странице или в Ваших заявках. Перейдите на одну из вышеперечисленных страниц и выберите 'Создать заявку'. Вы можете облегчить создание заявки добавив ваш авто в 'Гараж' в личном кабинете."
        ],
        [
            "image": UIImage(named: "help") as Any,
            "icon": UIImage(named: "dismiss") as Any,
            "text": "Как оставить заявку?",
            "message": "Вы можете создать заявку на главной странице или в Ваших заявках. Перейдите на одну из вышеперечисленных страниц и выберите 'Создать заявку'. Вы можете облегчить создание заявки добавив ваш авто в 'Гараж' в личном кабинете."
        ],
        [
            "image": UIImage(named: "podderzhka") as Any,
            "icon": UIImage(named: "arrow") as Any,
            "text": "Свяжитесь с нами?"
        ]
    ]
    
    // MARK: - Outlets
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.register(SupportCell.self, forCellReuseIdentifier: "supportCell")
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .lightBlueColor
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    
    // MARK: - Actions
    
    @objc private func goBack (sender: UIBarButtonItem) {
        navigationController?.popViewController(animated: true)
    }
        
        
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.addViews()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        self.setUpNav()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        self.navigationController?.navigationBar.isHidden = true
    }
    
    private func addViews () {
        self.view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.bottom.equalTo(view.safeAreaInsets)
            make.leading.trailing.equalToSuperview()
            make.top.equalToSuperview().offset(54)
        }
    }
    
    private func setUpNav () {
        self.navigationController?.navigationBar.isHidden = false
        self.navigationItem.title = "Поддержка"
        self.addBackIcon()
    }
    
    private func addBackIcon () {
        let backIcon = UIImage(named: "cancel")
        let backButton = UIBarButtonItem(image: backIcon, style: .plain, target: self, action: #selector(goBack(sender:)))
        backButton.tintColor = .greyColor
        navigationItem.leftBarButtonItem = backButton
    }
}

extension SupportViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if self.data[indexPath.row]["message"] == nil {
            self.openContactVC()
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "supportCell") as! SupportCell
        cell.updateUI(text: data[indexPath.row]["message"] as? String,
                      leftItem: data[indexPath.row]["image"] as! UIImage,
                      name: data[indexPath.row]["text"] as! String,
                      rightIcon: data[indexPath.row]["icon"] as! UIImage)
        cell.delegate = self
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 65))
        
        let titleLbl = UILabel()
        titleLbl.font = .systemFont(ofSize: 20, weight: .semibold)
        titleLbl.textColor = .darkBlueColor
        titleLbl.text = "Вопросы и ответы"
        
        headerView.addSubview(titleLbl)
        
        titleLbl.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(-25)
            make.leading.trailing.equalToSuperview().inset(16)
        }
        
        return headerView
    }
}

extension SupportViewController: SupportCellDelegate {
    func updateCells () {
        tableView.beginUpdates()
        tableView.endUpdates()
    }
    func openContactVC () {
        let contactUS = ContactUsVC()
        self.navigationController?.pushViewController(contactUS, animated: true)
    }
}



protocol SupportCellDelegate {
    func updateCells ()
    func openContactVC ()
}


final class SupportCell: UITableViewCell {
 
    
    private lazy var containerView: UIView = {
        let view = UIView()
        view.layer.cornerRadius = 10
        view.backgroundColor = .white
        view.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
        return view
    }()
    
    private lazy var columnStack: UIStackView = {
        let stack = UIStackView()
        stack.axis = .vertical
        stack.alignment = .fill
        stack.distribution = .equalSpacing
        stack.backgroundColor = .white
        return stack
    }()
    
    private lazy var navItemView: NavItemView = {
        let navItemView = NavItemView()
        navItemView.layer.cornerRadius = 10
        navItemView.backgroundColor = .white
        navItemView.arrowBtn.imageEdgeInsets = UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3)
        navItemView.arrowBtn.transform = CGAffineTransform(rotationAngle: .pi/4)
        return navItemView
    }()
    
    private lazy var textView: UIView = {
        let view = UIView()
        view.layer.cornerRadius = 10
        view.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var textLbl: UILabel = {
        let lbl = UILabel()
        lbl.textColor = .greyColor
        lbl.numberOfLines = 0
        return lbl
    }()
  
    private var hasContent: Bool = false
    private var isExpanded: Bool = true
    private var iconGesture: UITapGestureRecognizer!
    
    public var delegate: SupportCellDelegate!
    
    @objc private func onRightIconClick (sender: UIButton) {
        if hasContent {
            self.isExpanded.toggle()
            if isExpanded {
                self.addContent()
            } else {
                self.removeContent()
            }
            self.navItemView.arrowBtn.transform = !isExpanded ? CGAffineTransform(rotationAngle: .pi / 4) : .identity
            delegate.updateCells()
        } else {
            delegate.openContactVC()
        }
    }
    
    
    public func updateUI (text: String?=nil, leftItem: UIImage, name: String, rightIcon: UIImage) {
        
        hasContent = text != nil
        
        if text == nil || text!.isEmpty {
            self.navItemView.arrowBtn.transform = .identity
            navItemView.arrowBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            self.removeContent()
        } else {
            navItemView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
            self.addContent()
        }
        
        self.navItemView.updateUI(leftIcon: leftItem, title: name, rightIcon: rightIcon)
        self.textLbl.text = text
    }
    
    private func addViews() {
        self.containerView.backgroundColor = .lightBlueColor
        self.backgroundColor = .lightBlueColor
        self.selectionStyle = .none
        
        self.columnStack.addArrangedSubview(navItemView)
        self.contentView.addSubview(containerView)
        containerView.addSubview(columnStack)
        textView.addSubview(textLbl)
        
        
        self.navItemView.arrowBtn.addTarget(self, action: #selector(onRightIconClick(sender:)), for: .touchUpInside)
        
        containerView.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.leading.trailing.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().inset(8)
        }
        
        columnStack.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        textLbl.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(16)
        }
    }
    
    private func addContent () {
        self.columnStack.addArrangedSubview(textView)
    }
    
    private func removeContent () {
        columnStack.removeArrangedSubview(textView)
        textView.removeFromSuperview()
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.addViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


